package com.eystar.pdc.model;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.eystar.pdc.util.LoginUtil;
import com.jfinal.kit.Ret;
import com.jfinal.log.Log;

import cn.hutool.core.util.StrUtil;

public class Login{

	public final static Login dao = new Login();
	public final static Log logger = Log.getLog(Login.class);

	public Ret login(HttpServletRequest request, User user) {
		Ret ret = Ret.fail();
		
		User dbUser = User.dao.findFirstByColumnSecurity("user_name", user.getStr("user_name"));
		// 如果查询不到该用户
		if (dbUser == null) {
			logger.error("用户名不存在 = " + user.toJson());
			return ret.set("msg", "用户名或密码错误！");
		}
		// 如果密码不对
		if (StrUtil.isBlank(user.getStr("user_pass")) || 
				!LoginUtil.getSaltPassword(user.getStr("user_pass"),dbUser.getSalt()).equals(dbUser.getStr("user_pass"))) {
			logger.error("用户密码错误 = " + user.toJson());
			return ret.set("msg", "用户名或密码错误！");
		}
		// 如果用户被锁定
		if (dbUser.getInt("status").shortValue() == LoginUtil.LOGIN_USER_LOCK_ERROR) {
			logger.error("登录用户被锁定 = " + user.toJson());
			return ret.set("msg", "用户被锁定，请联系管理员！");
		}
		//加载缓存信息
		loadUserInfo(request, dbUser);
		
		// 更新用户的最后登录时间
		dbUser.set("last_login_time", System.currentTimeMillis()/1000);
		dbUser.update();
		
		return Ret.ok();
	}
	/**
	 * 加载用户session
	 * @param request
	 * @param dbUser
	 */
	public void loadUserInfo(HttpServletRequest request, User dbUser){
		logger.debug("当前登录成功用户信息 = " + dbUser.toJson());
		// 获取当前登录用户的角色
		Role role = Role.dao.findById(dbUser.getStr("role_id"));
		if (role != null) {
			logger.debug("当前登录用户角色为 = " + role.toJson());
			dbUser.put("role_id",role.getStr("id"));
			dbUser.put("role_name",role.getStr("role_name"));
			dbUser.put("role_flag",role.getInt("role_flag"));
		}
		// 获取当前登录用户的机构
		Org org = Org.dao.findOrgById(dbUser.getStr("org_id"));
		if (org != null) {
			logger.debug("当前登录用户机构为 = " + org.toJson());
			dbUser.put("org_id",org.getStr("id"));
			dbUser.put("org_name",org.getStr("org_name"));
		}
		
		Set<String> authorities = AuthSign.dao.findAuthSignSetByRole(role);
		logger.debug("登录成功后，当前登录用户的权限关键字 = " + authorities.toString());
		dbUser.put("authorities", authorities);
		
		// 刷新菜单资源信息
		Resource.dao.refresh(true);
		HttpSession session = request.getSession();
		session.setAttribute(LoginUtil.SESSION_CURRENT_USER, dbUser);
	}
	
}
